package chat.model;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.orm.SugarRecord;

import java.util.ArrayList;
import java.util.List;

import chat.network.http.SendRoomMessage;
import model.Message;
import model.RoomMessage;

/**
 * 群聊
 * Created by 凯 on 2015/10/31.
 */
public class RoomChatModel {
    public static final String OLDNUM = "30";

    List<RoomMessage> roomMessages = new ArrayList<RoomMessage>();

    public void setRoomMessages(List<RoomMessage> roomMessages) {
        this.roomMessages = roomMessages;
    }

    Long smallId = Long.MAX_VALUE;
    Long bigId = Long.MAX_VALUE;

    String roomId;

    // 设置房间id
    public void setRoomId(String roomId) {
        this.roomId = roomId;
    }

    // 初始化
    public void init()
    {
        List<RoomMessage> oldMsgs = SugarRecord.findWithQuery(RoomMessage.class, "Select * from RoomMessage where roomid = ? and id < ? order by id desc  limit 0,10",  roomId + "", smallId + "");
        if (oldMsgs != null && !oldMsgs.isEmpty())
        {
            smallId = oldMsgs.get(oldMsgs.size()-1).getId();
            bigId = oldMsgs.get(0).getId();
        }
        else
        {
            smallId = bigId = 0l;
        }
        for (RoomMessage message:oldMsgs)
        {
            roomMessages.add(0,message);
        }
    }

    // 获取新的
    public void getnew()
    {
        List<RoomMessage> newMsgs = SugarRecord.findWithQuery(RoomMessage.class,"Select * from RoomMessage where roomid = ? and id > ?",roomId+"",bigId+"");
        if (newMsgs != null && !newMsgs.isEmpty())
        {
            bigId = newMsgs.get(newMsgs.size()-1).getId();
        }

        roomMessages.addAll(newMsgs);
    }

    // 获取旧的
    public int getold()
    {
        List<RoomMessage> oldMsgs = SugarRecord.findWithQuery(RoomMessage.class, "Select * from RoomMessage where roomid = ? and id < ?  limit 0,?", roomId + "", smallId + "",OLDNUM);
        if (oldMsgs != null && !oldMsgs.isEmpty())
        {
            smallId = oldMsgs.get(oldMsgs.size()-1).getId();
        }
        roomMessages.addAll(0,oldMsgs);
        return oldMsgs.size();
    }

}
